/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useMemo } from 'react';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { Button, Input, message, Popconfirm, Space, Typography } from 'antd';
import { getComplaintList, setInnSmsStatus } from '@/services/yz/smsMonitor';
import ComplaintDrawer from './ComplaintDrawer';
import SmsTemplateDrawer from './SmsTemplateDrawer';
import moment from 'moment';
import SmsUpload from './SmsUpload';

const { Text } = Typography;
const SmsMonitorComplaint = () => {
  const actionRef = useRef<ActionType>();
  const [selectList, setSelectList] = useState<React.Key[]>([]);
  const [dataList, setDataList] = useState<Record<string, string>[]>([]);

  const batchOpen = useMemo(
    () =>
      !(
        selectList.length &&
        dataList.some((item) => selectList.includes(item.id) && item.storage_auth == '1')
      ),
    [selectList, dataList],
  );
  const batchClose = useMemo(
    () =>
      !(
        selectList.length &&
        dataList.some((item) => selectList.includes(item.id) && item.storage_auth != '1')
      ),
    [selectList, dataList],
  );

  const formatBatchId = (status: string) => {
    const arr = dataList.filter((item) => selectList.includes(item.id));
    if (status == 'open') {
      return arr
        .filter((item) => item.storage_auth != '1')
        .map((item) => item.cm_id)
        .toString();
    }
    if (status == 'close') {
      return arr
        .filter((item) => item.storage_auth == '1')
        .map((item) => item.cm_id)
        .toString();
    }
    return '';
  };

  const setStatus = async (params: { cm_id: string; storage_sms_auth: string }) => {
    const { code, msg } = await setInnSmsStatus(params);
    if (code == 0) {
      actionRef.current?.reload();
    } else {
      message.error(msg);
    }
  };
  const columns: ProColumns<Record<string, string>>[] = [
    {
      title: '',
      dataIndex: 'month',
      valueType: 'dateRange',
      hideInTable: true,
      fieldProps: {
        picker: 'month',
        format: 'YYYY-MM',
        allowClear: false,
      },
      initialValue: ['2022-06', '2022-08'],
      search: {
        transform: (value: any) => ({
          state_date: moment(value[0]).format('YYYY-MM'),
          end_date: moment(value[1]).format('YYYY-MM'),
        }),
      },
    },
    {
      title: '',
      dataIndex: 'searchContent',
      ellipsis: true,
      hideInTable: true,
      renderFormItem: () => {
        return <Input placeholder='输入驿站ID、注册手机号、驿站名称' />;
      },
    },

    {
      title: '月份',
      dataIndex: 'month',
      align: 'center',
      search: false,
    },
    {
      title: '驿站ID',
      dataIndex: 'cm_id',
      align: 'center',
      search: false,
    },
    {
      title: '驿站名称',
      dataIndex: 'inn_name',
      align: 'center',
      search: false,
    },
    {
      title: '注册电话',
      dataIndex: 'phone',
      align: 'center',
      search: false,
      render: (value) => <Text type='danger'>{value}%</Text>,
    },
    {
      title: '所属加盟商',
      dataIndex: 'league_name',
      align: 'center',
      search: false,
    },
    {
      title: '短信/云呼占比',
      dataIndex: 'notice_percentage',
      align: 'center',
      search: false,
      render: (value) => <Text type='danger'>{value}%</Text>,
    },
    {
      title: '入库数量',
      dataIndex: 'storage_num',
      align: 'center',
      search: false,
    },
    {
      title: '投诉单号',
      dataIndex: 'complaint_num',
      align: 'center',
      search: false,
    },
    {
      title: '投诉单号占比',
      dataIndex: 'complaint_percent',
      align: 'center',
      search: false,
      render: (value) => <Text type='danger'>{value}%</Text>,
    },
    {
      title: '历史投诉单号',
      dataIndex: 'complaint_total_num',
      align: 'center',
      search: false,
    },
    {
      title: '投诉详情',
      dataIndex: 'complaint_detail',
      align: 'center',
      search: false,
      render: (_, record) => (
        <ComplaintDrawer data={record}>
          <Button type='link'>详情</Button>
        </ComplaintDrawer>
      ),
    },
    {
      title: '允许仅入库不发短信',
      dataIndex: 'storage_auth',
      align: 'center',
      search: false,
      render: (_, record) => {
        const { storage_auth, cm_id } = record;
        const title = `确认${storage_auth == '1' ? '开启' : '关闭'}入库不发短信`;
        return (
          <>
            <Popconfirm
              title={title}
              disabled={storage_auth == '1'}
              onConfirm={setStatus.bind(null, { cm_id, storage_sms_auth: 'close' })}
            >
              <Button type='link' disabled={storage_auth == '1'}>
                关闭
              </Button>
            </Popconfirm>
            <Popconfirm
              title={title}
              onConfirm={setStatus.bind(null, { cm_id, storage_sms_auth: 'open' })}
              disabled={storage_auth != '1'}
            >
              <Button type='link' disabled={storage_auth != '1'}>
                开启
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'operate',
      align: 'center',
      search: false,
      render: (_, record) => (
        <SmsTemplateDrawer data={record}>
          <Button type='link'>推送投诉通知</Button>
        </SmsTemplateDrawer>
      ),
    },
  ];

  const requestTableData = async (values: Record<string, string>) => {
    const { current, ...rest } = values;
    const { code, data, msg } = await getComplaintList({
      page: current,
      status: 4,
      ...rest,
    });
    if (code == 0) {
      setDataList(current == '1' ? data.list : [...dataList, ...data.list]);
      return { data: data.list, total: data.total };
    } else {
      setDataList([]);
      message.error(msg);
      return { data: [], total: 0 };
    }
  };

  return (
    <>
      <DragTable>
        <ProTable<Record<string, string>>
          actionRef={actionRef}
          rowKey='id'
          request={requestTableData}
          rowSelection={{
            onChange: (ids) => setSelectList(ids),
            selectedRowKeys: selectList,
          }}
          columns={columns}
          options={false}
          headerTitle={
            <Space>
              <Popconfirm
                title='确定批量开启入库不发短信？'
                onConfirm={setStatus.bind(null, {
                  cm_id: formatBatchId('open'),
                  storage_sms_auth: 'open',
                })}
                disabled={batchOpen}
              >
                <Button type='primary' disabled={batchOpen}>
                  批量开启
                </Button>
              </Popconfirm>
              <Popconfirm
                title='确定批量关闭入库不发短信？'
                onConfirm={setStatus.bind(null, {
                  cm_id: formatBatchId('close'),
                  storage_sms_auth: 'close',
                })}
                disabled={batchClose}
              >
                <Button type='primary' disabled={batchClose}>
                  批量关闭
                </Button>
              </Popconfirm>

              <SmsTemplateDrawer ids={selectList}>
                <Button type='primary' disabled={selectList.length == 0}>
                  批量通知
                </Button>
              </SmsTemplateDrawer>
            </Space>
          }
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          scroll={{ x: 1400 }}
          search={{
            collapseRender: () => <></>,
            collapsed: false,
            optionRender: (_, __, dom) => [
              ...dom.reverse(),
              <SmsUpload key='upload' onReload={actionRef.current?.reload} />,
            ],
          }}
        />
      </DragTable>
    </>
  );
};

export default SmsMonitorComplaint;
